<!-- pages/order/index.vue -->
<template>
  <view class="order-container">
    <!-- 顶部状态选项卡 -->
    <scroll-view scroll-x class="status-tabs" show-scrollbar="false">
      <view class="tabs-wrapper">
        <view 
          v-for="(item, index) in orderStatus" 
          :key="index"
          class="tab-item"
          :class="{ active: currentStatus === item.value }"
          @click="switchStatus(item.value)"
        >
          <text>{{ item.label }}</text>
          <view v-if="currentStatus === item.value" class="tab-line"></view>
        </view>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <scroll-view 
      scroll-y 
      class="order-list"
      @scrolltolower="loadMore"
      :style="{ height: scrollHeight + 'px' }"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 空状态 -->
      <view v-if="filteredOrders.length === 0" class="empty-state">
        <image src="/images/order-empty.png" mode="aspectFit" class="empty-img"></image>
        <text class="empty-text">暂无相关订单~</text>
        <button class="go-shopping" @click="goShopping">去逛逛</button>
      </view>

      <!-- 订单项列表 -->
      <view v-else class="order-item" v-for="order in filteredOrders" :key="order.id" @click="toOrderDetail(order.id)">
        <!-- 订单头部信息 -->
        <view class="order-header">
          <text class="order-no">订单号：{{ order.assistiveOrderNumber }}</text>
         <text class="order-status" >{{ getStatusText(order.assistiveOrderState) }}</text>
        </view>

        <!-- 商品信息 -->
        <view class="goods-list">
          <view class="goods-item" v-for="(goods, idx) in order.goodsList" :key="idx">
            <image :src="goods.assisitveImg" mode="aspectFill" class="goods-img"></image>
            <view class="goods-info">
              <text class="goods-name">{{ goods.assisitveName }}</text>
              <text class="goods-spec" v-if="goods.assisitveType">{{ goods.assisitveType }}</text>
              <view class="goods-price-count">
                <text class="goods-price">¥{{ goods.assisitvePrice.toFixed(2) }}</text>
                <text class="goods-count">x{{ goods.assisitveOriginal }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 订单金额信息 -->
        <view class="order-footer">
          <view class="order-time">
            <text>下单时间：{{ order.createTime }}</text>
            <text v-if="order.createTime">支付时间：{{ order.createTime }}</text>
          </view>
          <view class="price-info">
            <text class="label">合计：</text>
            <text class="price">¥{{ order.assistiveOrderPrice.toFixed(2) }}</text>
          </view>
        </view>

        <!-- 操作按钮 -->
        <view class="action-buttons">
          <button 
            v-if="order.assistiveOrderState == 1" 
            class="btn pay-btn" 
            @click.stop="handlePay(order.id)"
          >去支付</button>
          <button 
            v-if="order.assistiveOrderState == 2" 
            class="btn log-btn" 
            @click.stop="viewLogistics(order.logisticsNo)"
          >查看物流</button>
          <button 
            v-if="order.assistiveOrderState == 3" 
            class="btn confirm-btn" 
            @click.stop="confirmReceipt(order.id)"
          >确认收货</button>
          <button 
            v-if="order.assistiveOrderState == 4" 
            class="btn more-btn" 
            @click.stop="moreOptions(order.id)"
          >更多</button>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import * as assistDev from '../../common/api/assistDev.js'
export default {
  data() {
    return {
      // 订单状态配置
      orderStatus: [
        { label: '全部', value: '' },
        { label: '待付款', value: '1' },
        { label: '待发货', value: '2' },
        { label: '待收货', value: '3' },
        { label: '已完成', value: '4' }
      ],
      currentStatus: '', // 当前选中状态
      orderList: [], // 全部订单列表
      filteredOrders: [], // 过滤后的订单列表
      page: 1, // 当前页码
      pageSize: 10, // 每页数量
      hasMore: true, // 是否有更多数据
      scrollHeight: 0, // 滚动区域高度
      isRefreshing: false // 下拉刷新状态
    }
  },
  onLoad() {
    // 初始化滚动区域高度
    this.getScrollHeight()
    // 加载初始数据
    this.getOrderList()
  },
  onPullDownRefresh() {
    // 小程序原生下拉刷新（兼容处理）
    this.isRefreshing = true
    this.page = 1
    this.hasMore = true
    this.getOrderList().finally(() => {
      this.isRefreshing = false
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    // 获取滚动区域高度
    getScrollHeight() {
      const systemInfo = uni.getSystemInfoSync()
      const headerHeight = 90 // 顶部选项卡高度（根据实际样式调整）
      this.scrollHeight = systemInfo.windowHeight - headerHeight
    },

    // 切换订单状态
    switchStatus(status) {
      if (this.currentStatus === status) return
      this.currentStatus = status
      this.page = 1
      this.hasMore = true
      this.getOrderList()
    },

    // 获取订单列表（模拟API请求）
    async getOrderList() {
      try {
        // 实际开发中替换为真实API调用
        // const res = await uni.request({
        //   url: '/api/order/list',
        //   data: { page: this.page, pageSize: this.pageSize, status: this.currentStatus }
        // })
        
        // 模拟数据
        // const mockData = Array.from({ length: this.currentStatus ? 5 : 12 }, (_, i) => ({
        //   id: `ORD${Date.now()}${i}`,
        //   orderNo: `ON${String(Math.random()).slice(2, 10).toUpperCase()}`,
        //   status: this.currentStatus ? Number(this.currentStatus) : [1,2,3,4][i%4],
        //   createTime: '2025-07-25 14:30:22',
        //   payTime: this.currentStatus > 1 ? '2025-07-25 14:35:10' : '',
        //   totalPrice: 199.00 + i*10,
        //   goodsList: [
        //     {
        //       image: 'https://via.placeholder.com/120',
        //       name: `商品名称${i+1}（${this.currentStatus ? ['手机','衣服','零食','图书'][i%4] : ''}）`,
        //       spec: this.currentStatus === 1 ? '颜色: 黑色; 尺寸: 128G' : '',
        //       price: 199.00 + i*5,
        //       count: 1
        //     }
        //   ],
        //   logisticsNo: this.currentStatus >= 2 ? 'SF1234567890' : ''
        // }))
		
		const param = {
			assistiveContactWx:uni.getStorageSync('openid_key')
		}
		assistDev.getMyOrder(
			param).then(result => {
			const mockData = result.data.data || []
			if (this.page === 1) {
			  this.orderList = mockData
			} else {
			  this.orderList = [...this.orderList, ...mockData]
			}
			// 过滤订单
			this.filteredOrders = this.orderList.filter(order => 
			  !this.currentStatus || order.status === Number(this.currentStatus)
			)
			console.log("filteredOrders",this.filteredOrders);
		}).catch(error => {
			console.log(error);
		})
		

        // if (this.page === 1) {
        //   this.orderList = mockData
        // } else {
        //   this.orderList = [...this.orderList, ...mockData]
        // }

        // // 过滤订单
        // this.filteredOrders = this.orderList.filter(order => 
        //   !this.currentStatus || order.status === Number(this.currentStatus)
        // )

        // this.hasMore = this.orderList.length < 20 // 模拟是否有更多数据

      } catch (error) {
        uni.showToast({
          title: '获取订单失败',
          icon: 'none'
        })
      }
    },

    // 加载更多数据
    loadMore() {
      if (!this.hasMore || this.isRefreshing) return
      this.page++
      this.getOrderList()
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        1: '待付款',
        2: '待发货',
        3: '待收货',
        4: '已完成',
        5: '已取消'
      }
      return statusMap[status] || '未知状态'
    },

    // 跳转订单详情
    toOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/order/detail?id=${orderId}`
      })
    },

    // 去支付
    handlePay(orderId) {
      uni.navigateTo({
        url: `/pages/payment/index?id=${orderId}`
      })
    },

    // 查看物流
    viewLogistics(logisticsNo) {
      uni.navigateTo({
        url: `/pages/logistics/detail?no=${logisticsNo}`
      })
    },

    // 确认收货
    confirmReceipt(orderId) {
      uni.showModal({
        title: '确认收货',
        content: '是否确认已收到商品？',
        success: (res) => {
          if (res.confirm) {
            // 调用确认收货API
            uni.showToast({
              title: '确认收货成功',
              icon: 'success'
            })
            this.getOrderList() // 刷新列表
          }
        }
      })
    },

    // 更多操作（示例）
    moreOptions(orderId) {
      uni.showActionSheet({
        itemList: ['申请售后', '删除订单'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.navigateTo({
              url: `/pages/after-sale/apply?id=${orderId}`
            })
          } else if (res.tapIndex === 1) {
            uni.showModal({
              title: '删除订单',
              content: '删除后无法恢复，确认删除？',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  // 调用删除订单API
                  uni.showToast({
                    title: '删除成功',
                    icon: 'success'
                  })
                  this.getOrderList() // 刷新列表
                }
              }
            })
          }
        }
      })
    },

    // 去购物
    goShopping() {
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.order-container {
  background: #f5f5f5;
  min-height: 100vh;
}

// 顶部状态选项卡
.status-tabs {
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 10;
  height: 90rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);

  .tabs-wrapper {
    display: flex;
    height: 100%;
    padding: 0 20rpx;
    
    .tab-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-size: 28rpx;
      color: #666;
      position: relative;
      padding: 0 10rpx;
      
      &.active {
        color: #ff4d4f;
        font-weight: 500;
      }
      
      .tab-line {
        position: absolute;
        bottom: 0;
        width: 40rpx;
        height: 4rpx;
        background: #ff4d4f;
        border-radius: 2rpx;
      }
    }
  }
}

// 订单列表
.order-list {
  padding: 20rpx;
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  
  .empty-img {
    width: 240rpx;
    height: 240rpx;
    margin-bottom: 30rpx;
  }
  
  .empty-text {
    font-size: 30rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
  
  .go-shopping {
    width: 280rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 30rpx;
    color: #fff;
    background: #ff4d4f;
    border-radius: 40rpx;
  }
}

// 订单项
.order-item {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.03);
}

// 订单头部
.order-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
  
  .order-no {
    font-size: 26rpx;
    color: #999;
  }
  
  .order-status {
    font-size: 28rpx;
    font-weight: 500;
    
    &.status-1 { color: #ff4d4f; } // 待付款
    &.status-2 { color: #ff9800; } // 待发货
    &.status-3 { color: #1890ff; } // 待收货
    &.status-4 { color: #07c160; } // 已完成
  }
}

// 商品列表
.goods-list {
  padding: 20rpx 0;
  
  .goods-item {
    display: flex;
    padding: 20rpx 0;
    
    .goods-img {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
      background: #f5f5f5;
    }
    
    .goods-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      
      .goods-name {
        font-size: 28rpx;
        color: #333;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2;
        overflow: hidden;
      }
      
      .goods-spec {
        font-size: 24rpx;
        color: #999;
        margin: 10rpx 0;
      }
      
      .goods-price-count {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .goods-price {
          font-size: 30rpx;
          color: #ff4d4f;
          font-weight: 500;
        }
        
        .goods-count {
          font-size: 24rpx;
          color: #999;
        }
      }
    }
  }
}

// 订单底部
.order-footer {
  display: flex;
  justify-content: space-between;
  padding-top: 20rpx;
  border-top: 1rpx solid #f5f5f5;
  
  .order-time {
    font-size: 24rpx;
    color: #999;
    line-height: 1.5;
  }
  
  .price-info {
    display: flex;
    align-items: center;
    
    .label {
      font-size: 28rpx;
      color: #333;
    }
    
    .price {
      font-size: 32rpx;
      color: #ff4d4f;
      font-weight: 500;
    }
  }
}

// 操作按钮
.action-buttons {
  display: flex;
  justify-content: flex-end;
  padding-top: 20rpx;
  
  .btn {
    margin-left: 20rpx;
    padding: 0 30rpx;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 28rpx;
    border-radius: 30rpx;
    background: #fff;
    border: 1rpx solid #eee;
  }
  
  .pay-btn { color: #fff; background: #ff4d4f; border-color: #ff4d4f; }
  .log-btn { color: #1890ff; border-color: #1890ff; }
  .confirm-btn { color: #07c160; border-color: #07c160; }
  .more-btn { color: #666; }
}
</style>